package com.qianfeng.dbsm.impl;

import com.qianfeng.dbsm.admin.entity.TbUserAddress;
import com.qianfeng.dbsm.admin.service.TbMemberService;
import com.qianfeng.dbsm.admin.service.TbUserAddressService;
import com.qianfeng.dbsm.common.Contants;
import com.qianfeng.dbsm.dao.TbOrderLogisticsDao;
import com.qianfeng.dbsm.entity.TbOrder;
import com.qianfeng.dbsm.entity.TbOrderLogistics;
import com.qianfeng.dbsm.service.TbOrderLogisticsService;
import com.qianfeng.dbsm.service.TbOrderService;
import com.qianfeng.dbsm.vo.LogisticsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class TbOrderLogisticsServiceImpl implements TbOrderLogisticsService {

    @Autowired
    TbOrderLogisticsDao logisticsDao;

    @Autowired
    TbOrderService orderService;

    @Autowired
    TbUserAddressService userAddressService;

    /**
     * 创建物流信息
     * @param logisticsVo
     * @return
     */
    @Override
    public int createLogistics(LogisticsVo logisticsVo) {

        TbOrderLogistics logistics = new TbOrderLogistics();
        logistics.setLogisticsCreateTime(new Date());
        logistics.setLogisticsResult(logisticsVo.getLogisticsResult());
        logistics.setLogisticsType(logisticsVo.getLogisticsType());
        logistics.setOrderNumber(logisticsVo.getOrderNumber());
        logistics.setDeliveryAmount(logisticsVo.getDeliveryAmount());
        logistics.setExpressNo(logisticsVo.getExpressNo());
        TbOrder order = orderService.queryByOrderNumber(logistics.getOrderNumber());
        int line = 0;
        if(order!=null){
            String addressId = order.getAddressId();
            TbUserAddress tbUserAddress = userAddressService.selectAddressById(Integer.valueOf(addressId));
            // 还有的信息 通过 orderNumber 查询tb_order表 中的 address_id 字段
            //然后通过address_id查询用户地址表 查询当前订单的发货地址
            logistics.setReceiverAddress(tbUserAddress.getReceiverAddress());
            logistics.setReceiverName(tbUserAddress.getReceiverName());
            logistics.setReceiverMobile(tbUserAddress.getReceiverMobile());
            logistics.setReceiverZip(tbUserAddress.getReceiverZip());
            line = logisticsDao.insert(logistics);
            //发货成功要改订单表状态
            orderService.updateOrderInfo(order.getOrderNumber(),Contants.OrderStatusCode.DELIVERED_NOT_RECEIVE.getCode());
        }else{
            throw new RuntimeException("订单号不存在，不可执行当前操作!!!");
        }
        return line;
    }

    /**
     * 通过订单编号查询发货信息
     * @param orderNumber
     * @return
     */
    @Override
    public List<TbOrderLogistics> queryByOrderNumber(String orderNumber) {
        return  logisticsDao.queryByOrderNumber(orderNumber);
    }
}
